<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件拖拽</title>
    <style>
        #box1 {
            width: 100px;
            height: 100px;
            background-color: rebeccapurple;
            position: absolute;
        }
    </style>

    <script type="text/javascript">
        window.onload =function() {
            // 拖拽box1元素
            var box1 = document.getElementById("box1");

            box1.onmousedown = function(event) {
                event = event || window.event
                // div的偏移量 = 鼠标.clientX - 元素.offsetLeft
                
                var ol = event.clientX - box1.offsetLeft;
                var ot = event.clientY - box1.offsetTop;

                document.onmousemove = function(event) {
                    event = event || window.event;
                    var left = event.clientX - ol;
                    var top = event.clientY - ot;

                    box1.style.left = left + "px";
                    box1.style.top = top + "px";
                };
                
                document.onmouseup = function() {
                    // 固定当前元素的位置
                    document.onmousemove = null;

                    // 取消当前这个松开事件
                    document.onmouseup = null;
                }
                // 当我们拖拽一个网页中的内容时，浏览器会默认区搜索引擎中搜索内容。
                // 此时会导致拖拽功能的异常，这个是浏览器提供的默认行为
                // 如果不希望发生这个行为，则可以通过return false来取消默认行为
                return false;

            }

        }
    </script>
</head>
<body>
    我是文字
    <div id="box1"></div>
</body>
</html>